package com.quarters.commen;

import com.quarters.bean.User;
import com.quarters.bean.UserInfo;
import com.quarters.service.*;
import com.quarters.util.Respons.ResponseUtil;
import com.quarters.util.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 张子艺
 * @packge com.controller.config
 * @data 2019-01-08 15:51
 * @project Currency
 */
@Configuration
public class BaseController {

    @Value("${weixin.redirectURL}")
    protected String redirectURL = "";
    @Autowired
    protected UserService userService;
    @Autowired
    protected XbxWxService xbxWxService;
    @Autowired
    protected UserInfoService userInfoService;
    @Autowired
    protected MenuService menuService;
    @Autowired
    protected QuartersService quartersService;
    @Autowired
    protected RepairService repairService;
    @Autowired
    protected InquiryService inquiryService;
    @Autowired
    protected  ArticleService articleService;
    @Autowired
    protected  ArticleOrderService articleOrderService;
    @Autowired
    protected NoticeService noticeService;
    @Autowired
    protected  NoticeOrderService noticeOrderService;
    @Autowired
    protected RoleQuartersService roleQuartersService;




    public User getUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        user = userService.getById(user.getId());
        return user;
    }

    public UserInfo getUserInfo(HttpSession session) {
        UserInfo user=   (UserInfo) session.getAttribute("userInfo");
        return user;
    }

    /***
     * 判断一个请求是否为AJAX请求,是则返回true
     * @param request
     * @return
     */
    public boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        //如果requestType能拿到值，并且值为 XMLHttpRequest ,表示客户端的请求为异步请求，那自然是ajax请求了，反之如果为null,则是普通的请求
        if (requestType == null) {
            return false;
        }
        return true;

    }

    /**
     * 程序异常
     * 因为有切面日志的原因如果控制层报错 则会打印两次日志  一次是请求的切点 一次是 本异常类的切点
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> serverException(Exception e) {
        if (e instanceof CommonException) {
            return ResponseUtil.RequestException(e.getMessage());
        }
        e.printStackTrace(System.out);
        return ResponseUtil.getExceptionMap();
    }






}
